package com.sali.b_design_pattern.g_singleton_pattern.lesson_destroy_singleton.b_serialize;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * @description:
 * @author: zhang hang
 * @date: 2023/3/19 19:03.
 * @version: 1.0
 */
public class Test2 {

    public static void main(String[] args) throws Exception {
        HungrySingletonSafe singleton1 = null;
        HungrySingletonSafe singleton2 = HungrySingletonSafe.getInstance();

        FileOutputStream fos = new FileOutputStream("HungrySingletonSafe.obj");
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        oos.writeObject(singleton2);
        oos.flush();
        oos.close();
        FileInputStream fis = new FileInputStream("HungrySingletonSafe.obj");
        ObjectInputStream ois = new ObjectInputStream(fis);
        // 这个地方在读取对象流时，若发现模板对象方法存在readResolve方法时，会直接把这个方法的结果返回
        singleton1 = (HungrySingletonSafe) ois.readObject();
        ois.close();
        System.out.println(singleton1);
        System.out.println(singleton2);
    }

}
